//
//  HomeService.swift
//  SCA
//
//  Created by tjun on 2025/9/5.
//

import UIKit

struct SCAModel {
    let title: String
    let icon: String
    let price: String
    let percent: String
    let percent_disp: String
    
    init(dict: [String: Any]) {
        self.title = dict.stringValue("title")
        self.icon = dict.stringValue("icon")
        self.price = dict.stringValue( "price")
        self.percent = dict.stringValue( "percent")
        self.percent_disp = dict.stringValue( "percent_disp")
    }
}


struct SCAChartModel {
    let dateString: String
    let value: String
    let timestamp: Int
}

struct SCAChartInfo {
    let min: Int
    let max: Int
    let lastUpdated: String
    let datas: [SCAChartModel]
    
    init(dict: [String: Any]) {
        self.min = dict.intValue("min")
        self.max = dict.intValue("max")
        self.lastUpdated = dict.stringValue( "last_updated")
      
        var datas: [SCAChartModel] = []

        if let datasDict = dict["data"] as? [String: String] {
            
            for (key, value) in datasDict {
                
                guard let date = Date.dateWithString(date: key, format: "yyyy-MM-dd HH:mm:ss") else {
                    continue
                }
                
                let chartModel = SCAChartModel(dateString: key, value: value, timestamp: Int(date.timeIntervalSince1970))
                datas.append(chartModel)
            }
        }
        
        self.datas = datas.sorted(by: { $0.timestamp < $1.timestamp })
    }
}


enum PowerType: String {
    case minting = "s"
    case matrix = "m"
    case differential = "g"
    case peer = "w"
}

struct PowerModel {
    let title: String
    let total: String
    let totalDisp: String
    let percent: String
    let info: String
    let color: String
    
    init(dict: [String: Any]) {
        self.title = dict.stringValue("title")
        self.total = dict.stringValue("total")
        self.totalDisp = dict.stringValue( "total_disp")
        self.percent = dict.stringValue("percent")
        self.info = dict.stringValue("info")
        self.color = dict.stringValue("color")
    }
}

struct PowerInfo {
    let total: String
    let totalDisp: String
    var cat: [PowerType: PowerModel] = [:]
    
    init(dict: [String: Any]) {
        self.total = dict.stringValue("total")
        self.totalDisp = dict.stringValue( "total_disp")
        
        if let catDict = dict["cat"] as? [String: Any] {
            for (key, value) in catDict {
                guard let modelDict = value as? [String: Any] else { continue }
                let model = PowerModel(dict: modelDict)
                if let powerType = PowerType(rawValue: key) {
                    self.cat[powerType] = model
                }
            }
        }
    }
}


enum BonusType: String {
    case sca = "sca"
    case aia = "aia"
    case aid = "aid"
}

struct BonusModel {
    
    let totalTitle: String
    let totalDisp: String
    let dailyTitle: String
    let dailyDisp: String
    
    init(dict: [String: Any]) {
        self.totalTitle = dict.stringValue("total_title")
        self.totalDisp = dict.stringValue("total_disp")
        self.dailyTitle = dict.stringValue( "daily_title")
        self.dailyDisp = dict.stringValue("daily_disp")
    }
}

struct PowerOverviewModel {
    let power: PowerInfo
    var bonus: [BonusType: BonusModel] = [:]
    
    init(power: [String: Any], bonus: [String : Any]) {
        
        for (key, value) in bonus {
            guard let modelDict = value as? [String: Any] else { continue }
            
            let model = BonusModel(dict: modelDict)
            if let powerType = BonusType(rawValue: key) {
                self.bonus[powerType] = model
            }
        }
        self.power = PowerInfo(dict: power)
    }
}

class HomeService {
    
    static func loadBannersData(success:(([String]) -> Void)? = nil,
                      failure:((_ error: Error) -> Void)? = nil) {
        
        if let cacheBanners = UserDefaults.standard.value(forKey: "banners") as? [String] {
            success?(cacheBanners)
        }

        NetworkManager.shared.post(url: APIEndpoint.events, parameters: nil, success: { data in
            guard let result = data as? [String: Any],
                  let banners = result["banners"] as? [String] else {
                return
            }
            UserDefaults.standard.set(banners, forKey: "banners")
            success?(banners)
        }, failure: failure)
    }
    
    static func loadTokensPriceData(completion:((SCAModel) -> Void)? = nil) {
        if let tokensPrice = UserDefaults.standard.value(forKey: "tokensPrice") as? String {
            if let dict = tokensPrice.toObject() as? [String: Any] {
                completion?(SCAModel(dict: dict))
            }
        }
        
        NetworkManager.shared.post(url: APIEndpoint.tokensPrice, parameters: nil, success: { data in
            guard let result = data as? [String: Any],
                  let dict = result["main"] as? [String: Any] else {
                return
            }
            if let string = dict.toJSONString() {
                UserDefaults.standard.set(string, forKey: "tokensPrice")
            }
            completion?(SCAModel(dict: dict))
        }, failure: nil)
    }
    
    static func loadTokensPriceChartData(completion:((SCAModel, SCAChartInfo) -> Void)? = nil) {
        NetworkManager.shared.post(url: APIEndpoint.tokensPrice, parameters: [
            "get_chart": true
        ], success: { data in
            guard let result = data as? [String: Any],
                  let dict = result["main"] as? [String: Any],
                  let chart = result["chart"] as? [String: Any] else {
                return
            }
            completion?(SCAModel(dict: dict), SCAChartInfo(dict: chart))
        }, failure: nil)
    }
 
    
    static func loadWorldPowerOverviewData(completion:((PowerOverviewModel) -> Void)? = nil) {
        if let tokensPrice = UserDefaults.standard.value(forKey: "worldPowerOverview") as? String {
            if let result = tokensPrice.toObject() as? [String: Any],
                let power = result["power"] as? [String: Any],
                let bonus = result["bonus"] as? [String: Any] {
                
                completion?(PowerOverviewModel(power: power, bonus: bonus))
            }
        }
        
        NetworkManager.shared.post(url: APIEndpoint.worldPowerOverview, parameters: nil, success: { data in
            guard let result = data as? [String: Any],
                  let power = result["power"] as? [String: Any],
                  let bonus = result["bonus"] as? [String: Any] else {
                return
            }
            
            if let jsonString = result.toJSONString() {
                UserDefaults.standard.set(jsonString, forKey: "worldPowerOverview")
            }
            completion?(PowerOverviewModel(power: power, bonus: bonus))
        }, failure: nil)
    }


}
